package com.phkj.qdh.utils

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable
import android.os.Build
import android.text.Editable
import android.text.TextWatcher
import android.util.TypedValue
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat.getSystemService
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.hjq.toast.ToastUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import java.lang.reflect.Method

fun View.gone() {
    this.visibility = View.GONE
}

fun View.invisible() {
    this.visibility = View.INVISIBLE
}

fun View.visible() {
    this.visibility = View.VISIBLE
}

fun TextView.clear() {
    this.text = ""
}

fun createNotificationChannel(
    context: Context, channelID: String, channelNAME: String, level: Int
): String? {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val manager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val channel = NotificationChannel(channelID, channelNAME, level);
        manager.createNotificationChannel(channel);
        channelID;
    } else {
        null;
    }
}


/**
 * edit监听
 */
fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(editable: Editable?) {
            afterTextChanged.invoke(editable.toString())
        }

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
    })
}

fun EditText.afterChangerEditable(afterTextChanged: (Editable) -> Unit) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(editable: Editable) {
            afterTextChanged.invoke(editable)
        }

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
    })
}

//float转px
val Float.dpToPx: Float
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP, this, Resources.getSystem().displayMetrics
    )

val Float.dpToSp: Float
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_SP, this, Resources.getSystem().displayMetrics
    )

//flow
inline fun Fragment.launchAndRepeatWithViewLifecycle(
    minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
    crossinline block: suspend CoroutineScope.() -> Unit
) {
    viewLifecycleOwner.lifecycleScope.launch {
        viewLifecycleOwner.lifecycle.repeatOnLifecycle(minActiveState) {
            block()
        }
    }
}

//文字粗体
fun TextView.fontBold() {
    this.paint.style = Paint.Style.FILL_AND_STROKE
    this.paint.strokeWidth = 0.8f
    this.invalidate()
}

//显示输入框的光标
fun showEditTextInput(edt: EditText) {
    val cls = EditText::class.java
    var method: Method
    try {
        method = cls.getMethod("setShowSoftInputOnFocus", Boolean::class.javaPrimitiveType)
        method.isAccessible = true
        method.invoke(edt, false)
    } catch (e: Exception) {
    }

    try {
        method = cls.getMethod("setSoftInputShownOnFocus", Boolean::class.javaPrimitiveType)
        method.isAccessible = true
        method.invoke(edt, false)
    } catch (e: Exception) {
    }

}

//资源文件转换为bitmap
fun drawableToBitmap(drawable: Drawable): Bitmap {
    //声明将要创建的bitmap
    var bitmap: Bitmap? = null
    //获取图片宽度
    val width = drawable.intrinsicWidth
    //获取图片高度
    val height = drawable.intrinsicHeight
    //图片位深，PixelFormat.OPAQUE代表没有透明度，RGB_565就是没有透明度的位深，否则就用ARGB_8888。详细见下面图片编码知识。
    val config = if (drawable.getOpacity() != PixelFormat.OPAQUE) {
        Bitmap.Config.ARGB_8888
    } else {
        Bitmap.Config.RGB_565;
    }
    //创建一个空的Bitmap
    bitmap = Bitmap.createBitmap(width, height, config)
    //在bitmap上创建一个画布
    val canvas = Canvas(bitmap)
    //设置画布的范围
    drawable.setBounds(0, 0, width, height)
    //将drawable绘制在canvas上
    drawable.draw(canvas)
    return bitmap
}


@RequiresApi(Build.VERSION_CODES.Q)
fun checkPermissions(
    context: Context, sArray: ArrayList<String>, todo: () -> Unit
) {//检测权限是否全部获取
    if (!XXPermissions.isGranted(context, sArray)) {
        XXPermissions.with(context).permission(sArray).request(object : OnPermissionCallback {
            override fun onGranted(permissions: MutableList<String>, all: Boolean) {
                if (!all) {
                    ToastUtils.show("获取部分权限成功，但部分权限未正常授予")
                    return
                }
                todo.invoke()
                ToastUtils.show("获取权限成功")
            }

            override fun onDenied(permissions: MutableList<String>, never: Boolean) {
                if (never) {
                    ToastUtils.show("被永久拒绝授权，请手动授予")
                    // 如果是被永久拒绝就跳转到应用权限系统设置页面
                    XXPermissions.startPermissionActivity(
                        context, permissions
                    )
                } else {
                    ToastUtils.show("获取权限失败")
                }
            }
        })
    } else {
        todo.invoke()
    }
}


@RequiresApi(Build.VERSION_CODES.Q)
fun justCheckPermissions(
    context: Context, sArray: ArrayList<String>, todo: () -> Unit
) {//检测权限是否全部获取
    if (!XXPermissions.isGranted(context, sArray)) {
        XXPermissions.with(context).permission(sArray).request(object : OnPermissionCallback {
            override fun onGranted(permissions: MutableList<String>, all: Boolean) {
                todo.invoke()
                ToastUtils.show("获取权限成功")
            }

            override fun onDenied(permissions: MutableList<String>, never: Boolean) {
                if (never) {
                    ToastUtils.show("被永久拒绝授权，请手动授予")
                    // 如果是被永久拒绝就跳转到应用权限系统设置页面
                    todo.invoke()
                } else {
                    todo.invoke()
                }
            }
        })
    } else {
        todo.invoke()
    }
}